<template>
  <div @click.stop="showModel" ref="colorModel" class="color">
    <div class="color" :style="{background:color.hex}"></div>
    <sketch-picker v-model="color" class="color-model" v-if="show==true"></sketch-picker>
  </div>
</template>

<script>
import {Sketch} from 'vue-color'

export default {
  name: "Color",
  props: {
    value: {
      type: String
    }
  },
  data() {
    return {
      color: {
        hex: this.value
      },
      show: false
    }
  },
  components: {
    'sketch-picker': Sketch,
  },
  methods: {
    showModel: function (event) {
      this.show = true;
      var that = this;
      var clickEvent = (e) => {
        if (!that.$refs.colorModel.contains(e.target)) {
          that.show = false;
          document.removeEventListener('click', clickEvent)

        }
      }
      document.addEventListener('click', clickEvent)
    }
  },
  watch: {
    color: {
      handler(newVal, oldVal) {
        this.$emit('input', newVal.hex);
      },
      immediate: true,
      deep: true
    }
  }
}
</script>

<style scoped>
.color {
  width: 20px;
  height: 20px;
  position: relative;
  border: 1px solid rgb(240,240,240);
  border-radius: 3px;
}

.color-model {
  position: absolute;
  z-index: 9999;
}
</style>
